package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.PermissionMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Override // 此方法用作数据库版登陆校验
    public User findUserByUsername(String username) {
        //redis process
        User userRedis = (User)redisTemplate.opsForValue().get("User");
        if(userRedis == null){
            //mysql process
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username",username);
            User user = baseMapper.selectOne(queryWrapper);
            if (user!=null){
                Integer userId = user.getId();
                List<Role> roles = roleMapper.findRolesByUserId(userId);
                for (Role role : roles) {
                    Integer roleId = role.getId();
                    List<Permission> permissions = permissionMapper.findPermissionsByRoleId(roleId);
                    role.setPermissions(permissions);
                }
                user.setRoles(roles);
            }
            return user;
        }else {
            return userRedis;
        }
    }

    @Override // 此方法用作修改权限登录密码
    public void changePassword(String username, String password) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);
        baseMapper.changePasswordByUsername(username,encode);
    }
}
